const express = require('express');
const router = express.Router();

const ManagerModel = require('../../model/managerModel');
const NavModel = require('../../model/navModel');
const FocusModel = require('../../model/focusModel');
const ArticleCateModel = require('../../model/articleCateModel');
const ArticleModel = require('../../model/articleModel');

// es6的属性名变量
const appModel = {
  ManagerModel: ManagerModel,
  NavModel, //字面量增强写法也可以
  FocusModel,
  ArticleCateModel,
  ArticleModel
}
// 获取：
//  1.appModel.ManagerModel
//  2.appModel['ManagerModel']

router.get('/', (req, res)=>{
  res.render('admin/main/index.html', {
    username: req.session.userinfo.username
  });
});

router.get('/welcome', (req, res)=>{
  res.send('欢迎来到后台管理中心');
});

// ajax实现状态修改
router.get('/changeStatus', async (req, res)=>{
  // 1.获取需要修改数据的id
  let id = req.query.id;
  // 2.获取数据库表
  let model = req.query.model + 'Model';
  // 3.获取需要修改的字段
  let field = req.query.field;
  let newFieldVal; //要更新的数据
  // 4.查询当前数据的状态 因为model指向一个字符串，所以不用加引号
  let result = await appModel[model].find({_id: id});
  // 5.修改状态 0->1  1->0
  if(result.length > 0){
    let tempField = result[0][field];
    tempField==1?newFieldVal={[field]: 0} : newFieldVal={[field]: 1};
    await appModel[model].updateOne({_id: id}, newFieldVal);
    res.send({
      success: true,
      message: '修改状态成功'
    })
  }else{
    res.send({
      success: false,
      message: '修改状态失败'
    })
  }
});

router.get('/changeNum', async (req, res)=>{
    try {
      let id = req.query.id;
      let model = req.query.model + 'Model';
      let field = req.query.field;
      let num = req.query.num;
      let result = await appModel[model].find({_id: id});
      console.log(result);
      if(result.length > 0){
        let newFieldVal = {
          [field]: num
        }
        await appModel[model].updateOne({_id: id}, newFieldVal);
        res.send({
          success: true,
          message: '修改数量成功'
        })
      }else{
        res.send({
          success: false,
          message: '修改数量失败'
        })
      };
    } catch (error) {
      res.send({
        success: false,
        message: '修改数量失败'
      })
    }
});

module.exports = router;